package com.example.rentsystem.servlet.pages;

import com.example.rentsystem.entity.House;
import com.example.rentsystem.entity.User;
import com.example.rentsystem.service.HouseService;
import com.example.rentsystem.service.impl.HouseServiceImpl;
import com.example.rentsystem.utils.ImageUtil;
import com.example.rentsystem.utils.ThymeleafUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.thymeleaf.context.Context;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

@MultipartConfig
@WebServlet("/modify-house")
public class ModifyHouseServlet extends HttpServlet {

    private HouseService houseService;

    @Override
    public void init() throws ServletException {
        houseService = new HouseServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = (User) req.getSession().getAttribute("user");
        if (user == null) {
            req.getSession().setAttribute("login-first", true);
            resp.sendRedirect("login");
            return;
        }
        Context context = new Context();
        context.setVariable("user", user);

        String id = req.getParameter("id");
        if (id != null && !id.equals("")) {
            House house = houseService.getHouse(Integer.parseInt(id));
            if (house.getOwnerId() != user.getId()) {
                resp.sendRedirect("index");
                return;
            }
            context.setVariable("house", house);
        }

        ThymeleafUtil.process("modify-house.html", context, resp.getWriter());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            session.setAttribute("login-first", true);
            resp.sendRedirect("login");
            return;
        }
        try {
            //创建磁盘工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //Servlet文件上传核心对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            List<FileItem> fileItems = fileUpload.parseRequest(req);
            Map<String, Object> params = new HashMap<>();
            //只能在这里获取参数 因为getParameter、getInputStream和getReader是互斥的，当流被其中一种方式读取后可能字节发生了改变，这时候用另外一种方法无论如何都获取不到的
            //所以在 fileUpload.parseRequest(request) 之后 即时用下方注释掉的代码处理request后 再尝试使用 request.getParameter去获取参数 会发现也都是null
            for (FileItem fileItem : fileItems) {
                //是普通表单字段
                if (fileItem.isFormField()) {
                    params.put(fileItem.getFieldName(), fileItem.getString("UTF-8"));
                } else {
                    //是文件 这里只上传一个文件 所以无需List处理
                    params.put(fileItem.getFieldName(), fileItem);
                }
            }
            String id = (String) params.get("id");
            if (id == null || id.equals("")) {
                resp.sendRedirect("personal-house");
                return;
            }
            House house = houseService.getHouse(Integer.parseInt(id));
            if (house == null) {
                resp.sendRedirect("personal-house");
                return;
            }
            String name = (String) params.get("name");
            String price = (String) params.get("price");
            String location = (String) params.get("location");
            String desc = (String) params.get("desc");
            String room = (String) params.get("room");
            String area = (String) params.get("area");
            if (name.equals("") || location.equals("") || desc.equals("") || room.equals("") || area.equals("")) {
                resp.sendRedirect("personal-house");
                return;
            }
            house.setName(name);
            house.setPrice(Integer.parseInt(price));
            house.setLocation(location);
            house.setDesc(desc);
            house.setRoom(room);
            house.setArea(Integer.parseInt(area));

            FileItem uploadFile = (FileItem) params.get("pic");
            if (!uploadFile.getName().equals("")) {
                UUID uuid = UUID.randomUUID();
                String pic = "/assets/images/" + uuid + ".jpg";
                if (!ImageUtil.write(uploadFile, uuid))
                    pic = String.format("/assets/img/icon/%s.svg", new Random().nextInt(6) + 1);
                ImageUtil.delete(house.getPic());
                house.setPic(pic);
            }
            houseService.editHouse(house);
        } catch (Exception e) {
            e.printStackTrace();
        }
        resp.sendRedirect("personal-house");
    }
}
